import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, Drawer, Form, FormProps, Input, Select, Space } from 'antd';

import Upload from '@/components/upload';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  equRepairRegularPlanAdd,
  equRepairRegularPlanUpdate
} from '@/services/bizApi/shebaodingqijianxiujihuajiekou';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );
  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        dutyUserName: userInfo?.data?.filter((item) => item.id === values?.dutyUserId)?.[0]
          ?.fullName,
        cron: '0 ' + values?.cron
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? equRepairRegularPlanUpdate(query)
        : equRepairRegularPlanAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增定期维修记录',
          edit: '编辑定期维修记录',
          detail: '定期维修记录详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="负责人"
          name="dutyUserId"
          rules={[
            {
              required: true,
              message: '请选择负责人'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择负责人"
            showSearch={true}
            optionFilterProp="label"
            options={
              userInfo?.data?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            }
          />
        </Form.Item>
        <Form.Item
          label="详情"
          name="content"
          rules={[
            {
              required: true,
              message: '请输入详情'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入详情" />
        </Form.Item>
        <Form.Item
          label="处置情况"
          name="handleSituation"
          rules={[
            {
              required: true,
              message: '请输入处置情况'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入处置情况" />
        </Form.Item>
        <Form.Item
          label="上传附件"
          name="attachment"
          rules={[
            {
              required: false,
              message: '请上传附件'
            }
          ]}
        >
          <Upload
          // base64
          //  accept="image/*"
          >
            <Button>上传</Button>
          </Upload>
        </Form.Item>
        <Form.Item
          label="状态"
          name="status"
          rules={[
            {
              required: true,
              message: '请选择状态'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择状态"
            options={[
              {
                label: '待处理',
                value: 1
              },
              {
                label: '已完成',
                value: 3
              }
            ]}
          />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
